import { useEffect, useState, useRef } from 'react'
import { Form, Input, Button, Table, Space, Popconfirm, message } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import type { TableProps } from 'antd'

import dayjs from 'dayjs'
import './index.scss'

import Pagination from '@/components/pagination'
import DataProcess from './DataProcess'

import { getUserListData, deleteUserData } from '@/api/home'

interface callback {
  openModal: (parameter: boolean, data?: UserData.User) => void
}
const User = () => {
  const columnList: TableProps['columns'] = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age'
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      render: (value: number) => {
        return value ? '男' : '女'
      }
    },
    {
      title: '出生日期',
      dataIndex: 'birth',
      key: 'birth',
      render: (value: string) => {
        return dayjs(value).format('YYYY-MM-DD')
      }
    },
    {
      title: '地址',
      dataIndex: 'addr',
      key: 'addr'
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 120,
      align: 'center',
      render: (_, record) => (
        <Space>
          <Button
            size="small"
            onClick={() => handleOpen('edit', record as UserData.User)}
          >
            编辑
          </Button>
          <Popconfirm
            title="提示"
            description="此操作将删除该用户，是否继续？"
            onConfirm={() => handleDelete(record as UserData.User)}
          >
            <Button size="small" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]

  // 创建 ref
  const childRef = useRef<callback>(null)

  const [messageApi, contextHolder] = message.useMessage()

  const [referQuery, setReferQuery] = useState({
    name: '',
    page: 1,
    limit: 10
  })
  const [tableData, setTableData] = useState<UserData.User[]>([])
  const [total, setTotal] = useState(0)
  // 搜索
  const handleSearch = (values: { username: string }) => {
    setReferQuery({
      ...referQuery,
      name: values.username,
      page: 1
    })
    loadListData()
  }

  // 打开弹窗
  const handleOpen = (type: string, item?: UserData.User) => {
    childRef.current?.openModal(type === 'edit' ? true : false, item)
  }

  // 删除操作
  const handleDelete = async (record: UserData.User) => {
    const { message } = await deleteUserData(record.id)
    messageApi.success(message, 1, () => {
      loadListData()
    })
  }

  // 加载列表数据
  const loadListData = async () => {
    const { list, count } = await getUserListData(referQuery)

    setTableData(list)
    setTotal(count)
  }

  // 分页切换
  const handleChange = (value: number) => {
    setReferQuery({ ...referQuery, page: value })
    loadListData()
  }

  useEffect(() => {
    loadListData()
  }, [])

  return (
    <div className="user-view">
      {contextHolder}
      <div className="container">
        <div className="search-bar">
          <Form layout="inline" size="small" onFinish={handleSearch}>
            <Form.Item label="用户名" name="username">
              <Input placeholder="请输入用户名" allowClear />
            </Form.Item>
            <Form.Item label={null}>
              <Button type="primary" htmlType="submit">
                搜索
              </Button>
            </Form.Item>
            <Form.Item label={null}>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => handleOpen('add')}
              >
                新增
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div className="data-list">
          <Table
            columns={columnList}
            dataSource={tableData}
            rowKey={'id'}
            bordered
            pagination={false}
            sticky
          />
        </div>
      </div>
      <div className="pagination">
        <Pagination
          total={total}
          current={referQuery.page}
          handleChange={handleChange}
        />
      </div>

      <DataProcess ref={childRef} handleSuccess={loadListData} />
    </div>
  )
}

export default User
